<template>
  <component
    class="x-img"
    :is="background ? 'span' : 'img'"
    v-bind="$props"
    :src="background ? null : mySrc"
    :background="null"
    :defaultSrc="null"
    @load="handleLoad"
    @error="handleError">
    <slot></slot>
  </component>
</template>

<script>
  export default {
    componentName: 'EImg',
    props: {
      alt: {
        type: String
      },
      src: {
        type: String
      },
      srcset: {
        type: String
      },
      background: {
        type: Boolean,
        default: false
      },
      defaultSrc: {
        type: String,
        default: '/static/images/default/img.png'
      }
    },
    computed: {
      mySrc () {
        return this.src || this.defaultSrc
      }
    },
    watch: {
      src (value) {
        if (value) {
          this.background && this.backgroundLoad(value) // 设置成背景图片
        }
      }
    },
    mounted () {
      this.background && this.backgroundLoad(this.mySrc) // 设置成背景图片
    },
    methods: {
      backgroundLoad (src) {
        let image = new Image()
        image.onload = () => {
          this.$el.style.backgroundImage = `url(${src})`
          this.$emit('load', {target: this.$el})
        }
        image.onerror = () => {
          if (this.src && this.src.indexOf && this.src.indexOf(this.defaultSrc) === -1) {
            this.$el.setAttribute('error-src', src)
            this.$el.style.backgroundImage = `url(${this.defaultSrc})`
            this.$emit('error', {target: this.$el})
          }
        }
        image.src = src
      },
      handleLoad (e) {
        this.$emit('load', e)
      },
      handleError (e) {
        if (this.$el.src.indexOf(this.defaultSrc) === -1) {
          this.$el.setAttribute('error-src', this.$el.src)
          this.$el.src = this.defaultSrc
          this.$emit('error', e)
        }
      }
    }
  }
</script>
